import "./index.less"
import { Space, Table, Tag, Input, Button, message, TablePaginationConfig, Modal, Form, Switch } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, PlusOutlined, ArrowRightOutlined } from '@ant-design/icons';
import { getActiveList, jionActive, myActive } from "@/api/active"
import { useEffect, useRef, useState } from "react";
import systme from "@/api/constant"
import { useNavigate } from "react-router-dom";

interface activeType {
    "content": string,
    "count": number,
    "endDate": string,
    "id": string,
    "pageIndex": number,
    "pageSize": number,
    "pubDate": string,
    "title": string,
    "userId": string
}

let userId = JSON.parse(sessionStorage.getItem("user") as string).id
let searchValue = {
    title: '',
    account: '',
    address: '',
    pageIndex: 1,
    pageSize: 10,
    userId
}
let userName = JSON.parse(sessionStorage.getItem("user") as string).account

export default function active() {
    const router = useNavigate()

    const handlerSearch = (e: any) => {
          searchValue.title = e.target.value
    }
    const search = () => {
        initActiveList()
    }

    const handlerAdd = () => {
        router("/home/activeCreat")
    }

    useEffect(() => {
        initClearDate()
        initActiveList()

    }, [])


    const columns: ColumnsType<activeType> = [
        {
            title: '活动名称',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '开始时间',

            key: 'pubDate',
            render: (_, record: activeType) => (
                <div >
                    {record.endDate && record.pubDate.slice(0, 10)}
                </div>
            ),

        },

        {
            title: '结束时间',
            key: 'endDate',
            render: (_, record: activeType) => (
                <div >
                    {record.endDate && record.endDate.slice(0, 10)}
                </div>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: activeType) => (
                <Space size="middle">
                    {userName != 'admin' && <a onClick={() => { handlerJion(record) }}> 参加活动</a>}
                    {userName == 'admin' &&<a onClick={() => { handlerEdit(record) }}> 编辑活动</a>}
                </Space>
            ),
        },
    ];
    const handlerSee = (e: activeType)=>{
        router("/home/activeInfo", { state: e })
    }

    const handlerEdit = (e: activeType) => {
        router("/home/activeCreat", { state: e })
    }
    const handlerJion = (e: activeType) => {
        jionActive({ activityId: e.id, userId }).then((res) => {
            if (res.code == 200) {
                message.success("参加成功")
                initActiveList()
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
        }).catch((err) => {
            message.error(systme.ERROR_MESSAGE)
        })
    }
    const initClearDate = ()=>{
         searchValue = {
            title: '',
            account: '',
            address: '',
            pageIndex: 1,
            pageSize: 10,
            userId
        }
    }


    const [loading, setLoading] = useState(true)
    const [data, setData] = useState<activeType[]>([])
    const PageChange = (page: number, pageSize: number) => {
        searchValue.pageIndex = page
        searchValue.pageSize = pageSize
        setLoading(true)
        setConfig({ ...saveValue.current, pageSize, current: page })
        initActiveList()
    }

    const initActiveList = (data = searchValue) => {
        setLoading(true)
        getActiveList(data).then((res) => {
            if (res.code == 200) {
                setData(res.data.list)
                setConfig({ ...saveValue.current, total: res.data.total })
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
            setLoading(false)
        }).catch((error) => {
            message.error(error || systme.ERROR_MESSAGE)
            setLoading(false)
        })

    }


    let pageConfig: TablePaginationConfig = {
        position: ['bottomCenter'],
        total: 0,
        showTotal: (total: number) => `共 ${total} 条`,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        onChange: PageChange,
        pageSize: 10,
        current: 1

    }
    let [config, setConfig] = useState((pageConfig))
    let saveValue = useRef<TablePaginationConfig>()
    useEffect(() => {
        //储存数据
        saveValue.current = config
    }, [config])
    const handlerMyActive = () => {
        searchValue.pageIndex = 1
        myActive(searchValue).then((res) => {
            if (res.code == 200) {
                setData(res.data.list)
                setConfig({ ...saveValue.current, total: res.data.total })
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
            setLoading(false)
        }).catch((error) => {
            message.error( systme.ERROR_MESSAGE)
            setLoading(false)
        })
    }

    return (
        <div className="box_views">
            <div className="header flex">
                <div className="header_search flex">
                    <div className="item">
                        <Input placeholder="请输入活动名称" allowClear onChange={(e: unknown) => { handlerSearch(e) }} />
                    </div>
                    <Button type="primary" icon={<SearchOutlined />} size="middle" onClick={search}>查询</Button>

                </div>
                <div className="addBtn">
                    {userName=='admin'&&<Button type="primary" size="middle" onClick={handlerAdd}>创建活动 <ArrowRightOutlined /></Button>}
                </div>
            </div>
            <Table columns={columns} dataSource={data} pagination={config} rowKey={item => item.id} loading={loading} />
        </div>
    )
}